package com.chendx.store.seckill.mq.listener;

import com.alibaba.fastjson.JSON;
import com.chendx.model.seckill.pojo.SeckillOrder;
import com.chendx.model.seckill.vo.SeckillStatus;
import com.chendx.store.common.constants.seckill.SeckillConstants;
import com.chendx.store.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Created by chendx o 2022/4/24.
 */
@Component
@RabbitListener(queues = "queue.seckillordertimer")
public class SeckillOrderMessageListener {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitHandler
    public void message(String message){
        SeckillStatus seckillStatus = JSON.parseObject(message, SeckillStatus.class);
        String username = seckillStatus.getUsername();
        Object ojb = redisTemplate.boundHashOps(SeckillConstants.SECKILL_ORDER).get(username);
        if (!StringUtils.isEmpty(ojb)){
            SeckillOrder seckillOrder = JSON.parseObject(ojb.toString(),SeckillOrder.class);
            if (seckillOrder != null){
                System.out.println("准备回滚---"+seckillStatus);
                seckillOrderService.close(username);
            }
        }
    }
}
